package com.pansoft.openplanet.activity;

import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.bean.EscrowAccountListBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.fragment.BottomWalletChooseDialogFragment;
import com.pansoft.openplanet.fragment.RechargeDialogFragment;
import com.pansoft.openplanet.util.DecimalDigitsInputFilter;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.UTXOTransactionManager;
import com.pansoft.openplanet.widget.BlockChainFeeSeekBar;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static androidx.fragment.app.DialogFragment.STYLE_NO_FRAME;

/**
 * 托管账户充值界面
 *
 * @author yqs
 */

public class EscrowRechargeActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvTitle;//标题
    private TextView tvBalance;//余额
    private EditText tvReceiveAddress;//托管地址
    private EditText etMoney;//输入转账金额
    private LinearLayout llPay;//付款地址layout
    private LinearLayout llAddress;
    private TextView tvWallet;//钱包名称

    private TextView tvPay;//付款地址

    private TextView tvBalanceUnit;
    private Button butNext;

//    private ImageView ivChooseWallet;//箭头
//    private LinearLayout llExpense;//矿工费布局
//    private TextView tvExpense;//.0004 ether
//    private ImageView ivMinerFeeChoose;
//    private LinearLayout llSeekbar;//serkbar
//    private TextView tvMin;//0.004
//    private SeekBar seekBar;
//    private TextView tvMax;//0.006

    private LinearLayout llAccountContainer;//eos账户选择
    private LinearLayout llAccount;
    private TextView tvAccount;

    private EscrowAccountListBean.AssetsBean assetsBean;
    private AccountDao accountDao;
    private List<WalletBean> walletBeans = new ArrayList<>();


//    //默认手续费
//    private String gas = "0.0004";
//    //默认手续费
//    private String gas_unit = "ether";
    //默认链
    private int ipaChainId = IPAssetsConstant.CHAIN_ID_ETH;
    private String curAddress;
    private Account curAccount;
    private String chainBalance;//连余额
    private String tokenBalance;//代币余额

    private BlockChainFeeSeekBar blockFeeSekbar;


    public static void start(Context context, EscrowAccountListBean.AssetsBean assetsBean) {
        Intent starter = new Intent(context, EscrowRechargeActivity.class);
//       starter.putExtra();
        starter.putExtra("assetsBean", assetsBean);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity_escrow_escrow_recharge);
        initView();
        initData();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        setSwipeBackEnable(false);
        tvBalance = (TextView) findViewById(R.id.tv_balance);
        tvReceiveAddress = (EditText) findViewById(R.id.tv_receive_address);
        etMoney = (EditText) findViewById(R.id.et_money);
        llPay = (LinearLayout) findViewById(R.id.ll_pay);
        llAddress = (LinearLayout) findViewById(R.id.ll_address);
        tvWallet = (TextView) findViewById(R.id.tv_wallet);
        tvPay = (TextView) findViewById(R.id.tv_pay);

//        ivChooseWallet = (ImageView) findViewById(R.id.iv_choose_wallet);
//        llExpense = (LinearLayout) findViewById(R.id.ll_expense);
//        tvExpense = (TextView) findViewById(R.id.tv_expense);
//        ivMinerFeeChoose = (ImageView) findViewById(R.id.iv_miner_fee_choose);
//        llSeekbar = (LinearLayout) findViewById(R.id.ll_seekbar);
//        llSeekbar.setVisibility(View.GONE);
//        tvMin = (TextView) findViewById(R.id.tv_min);
//        seekBar = (SeekBar) findViewById(R.id.seekBar);
//        tvMax = (TextView) findViewById(R.id.tv_max);
//        tvExpense.setOnClickListener(this);

        llAccountContainer = (LinearLayout) findViewById(R.id.ll_account_container);
        llAccount = (LinearLayout) findViewById(R.id.ll_account);
        llAccount.setOnClickListener(this);
        tvAccount = (TextView) findViewById(R.id.tv_account);
        tvBalanceUnit = (TextView) findViewById(R.id.tv_balance_unit);
        butNext = (Button) findViewById(R.id.but_next);
        butNext.setOnClickListener(this);
        llAddress.setOnClickListener(this);
        etMoney.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8)});
        etMoney.addTextChangedListener(new NumberTextWatcher(etMoney));
        blockFeeSekbar = (BlockChainFeeSeekBar) findViewById(R.id.block_fee_sekbar);

    }

//    private void initSeekBar() {
////        //btc的，1000到10000 feePerKb
////        if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
////            //修改默认数值
////            gas = "1000";
////            tvExpense.setText(gas);
////            tvMin.setText("1000");
////            tvMax.setText("10000");
////            seekBar.setMax(9000);
////            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
////                @Override
////                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
////                    gas = String.valueOf(progress + 1000);
////                    tvExpense.setText(gas + " feePerKb");
////                }
////
////                @Override
////                public void onStartTrackingTouch(SeekBar seekBar) {
////
////                }
////
////                @Override
////                public void onStopTrackingTouch(SeekBar seekBar) {
////
////                }
////            });
////        } else {
////            //最小0.0004，最大0.006
////            seekBar.setMax(56);
////            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
////                @Override
////                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
////                    gas = BalanceUtil.formatPrice(new BigDecimal((double) (progress + 4) / 10000)
////                            .doubleValue(), true, 4);
////                    //更新矿工费金额
////                    if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH) {
////                        tvExpense.setText(gas + " ether");
////                    } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
////                        tvExpense.setText(gas + " eos");
////                    } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_TURBOCHAIN) {
////                        tvExpense.setText(gas + " pwr");
////                    }
////                }
////
////                @Override
////                public void onStartTrackingTouch(SeekBar seekBar) {
////
////                }
////
////                @Override
////                public void onStopTrackingTouch(SeekBar seekBar) {
////
////                }
////            });
////        }
////    }
   private void  initSeekBar(){
       blockFeeSekbar.setChainId(ipaChainId);
    }

    private void initData() {
        assetsBean = (EscrowAccountListBean.AssetsBean) getIntent().getSerializableExtra("assetsBean");
        accountDao = new AccountDao(this);
        tvTitle.setText(assetsBean.getCoinName() + " "+ResStringUtil.getString(R.string.open_planet_charge));
        tvBalanceUnit.setText(assetsBean.getCoinName());
        ipaChainId = Integer.valueOf(assetsBean.getBlockchainId());
        if (ipaChainId == IPAssetsConstant.CHAIN_ID_ETH ||ipaChainId==IPAssetsConstant.CHAIN_ID_ETE
               ) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.getChainEnumByChainId(ipaChainId));
//            gas_unit = "ether";
        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
            initLocalWalletData(IPAssetsConstant.ChainEnum.BTC);

        } else if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            initLocalWalletData(EosNetParamUtil.getEosChainEnum());

        } else if (ipaChainId == IPAssetsConstant.CHAIN_ID_TURBOCHAIN) {
//            gas_unit = " pwr";
            curAccount = accountDao.getMainAccount();
            curAddress = curAccount.getAddress();
            if (curAccount != null) {
                WalletBean walletBean = new WalletBean.Builder()
                        .accountName(curAccount.getAcccountName())
                        .avatar(curAccount.getAccountAvatar())
                        .address(curAccount.getAddress())
                        .balance("0")
                        .isSelected(true)
                        .build();
                walletBeans.add(walletBean);
            }
            setPayData();
            requestAccountBalance();
        }
        if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC || ipaChainId == EosNetParamUtil.getEosChainId()) {
            blockFeeSekbar.setVisibility(View.INVISIBLE);
        }
        initSeekBar();
        updateView();

    }

    private void updateView() {
//        tvExpense.setText(gas + " " + gas_unit);
    }

    /**
     * 设置付款地址信息
     */
    private void setPayData() {
        if (curAccount == null) {
            return;
        }
        tvPay.setText(curAccount.getAddress());
        tvWallet.setText(curAccount.getAcccountName());
    }

    /* 初始化本地钱包数据，根据intent里的类型，决定是哪一类账户
     * @param blockChainEnum ETH，BTC等
     */
    private void initLocalWalletData(IPAssetsConstant.ChainEnum blockChainEnum) {
        List<Account> accountList;
        if (ipaChainId == EosNetParamUtil.getEosChainId()) {
            accountList = accountDao.getAllActivatedEosAccount(blockChainEnum);
        } else {
            accountList = accountDao.getAllChildAccount(blockChainEnum);
        }
        if (accountList != null) {
            for (int i = 0; i < accountList.size(); i++) {
                Account account = accountList.get(i);
                if (account.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
                    //观察钱包不能转账
                    continue;
                }
                WalletBean walletBean = new WalletBean.Builder()
                        .accountName(account.getAcccountName())
                        .avatar(account.getAccountAvatar())
                        .address(account.getAddress())
                        .balance("0")
                        .build();

                walletBeans.add(walletBean);

            }
            if (accountList.size() > 0) {
                curAccount = accountList.get(0);
                curAddress = curAccount.getAddress();
                setPayData();
                requestAccountBalance();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.but_next) {
            //下一步
            String inputAmount = etMoney.getText().toString().trim();
            if (TextUtils.isEmpty(inputAmount)) {
                ToastUtils.showShort(R.string.open_planet_input_transfer_amount);
                return;
            }

            if (tvPay.getText().toString().equals("")) {
                ToastUtils.showShort(R.string.open_planet_select_pay_address);
                return;
            }

            showTransferConfirm();

        } else if (id == R.id.tv_expense || id == R.id.iv_miner_fee_choose) {
            //选择矿工费用
//            llSeekbar.setVisibility((llSeekbar.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE));
        } else if (id == R.id.ll_address) {
            //选择钱包
            showWalletChoose();
        } else if (id == R.id.ll_account) {
            //选择Eos钱包账户
            changeAccountAlert();
        }
    }


    /**
     * 请求账户余额
     */
    public void requestAccountBalance() {
        HashMap<String, String> map = new HashMap<>();
//>chainId    链编号(2是以太坊、4是涡链)
//>accountAddress 账户地址
//>coinAddress 合约地址（不是智能合约不用传）
//>coinDecimals 合约单位进制位数（不是智能合约不用传）

        if (curAccount == null) {
            return;
        }
        map.put("chainId", assetsBean.getBlockchainId());
        if (assetsBean.getCoinAddress() != null && !"".equals(assetsBean.getCoinAddress())) {
            map.put("coinAddress", assetsBean.getCoinAddress());
        }
        map.put("accountAddress", tvPay.getText().toString());
        map.put("coinDecimals", assetsBean.getCoinDecimals() + "");
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/balance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                try {
                    //   {"result":"success","chainBalance":"0.00000000","tokenBalance":"0.00000000"}
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if ("success".equals(jsonObject.optString("result"))) {
                        chainBalance = jsonObject.optString("chainBalance", "0.00000000");
                        if (assetsBean.getCoinAddress() != null && !"".equals(assetsBean.getCoinAddress())) {
                            tokenBalance = jsonObject.optString("tokenBalance", "0.00000000");
                            tvBalance.setText(tokenBalance);
                        } else {
                            tvBalance.setText(chainBalance);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.common_text_http_request_fail);
                }
            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                ToastUtils.showShort(R.string.common_text_http_request_fail);
            }
        });

    }

    /**
     * 切换钱包
     */
    private void showWalletChoose() {

        BottomWalletChooseDialogFragment bottomWalletChooseDialogFragment = new
                BottomWalletChooseDialogFragment();
        bottomWalletChooseDialogFragment.setData(this, walletBeans, ipaChainId);
        bottomWalletChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomWalletChooseDialogFragment.hideBalace(true);
        bottomWalletChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomWalletChooseDialogFragment.setOnWalletSelectChangedListener(new BottomWalletChooseDialogFragment.OnWalletSelectChangedListener() {
            @Override
            public void onWalletChanged(WalletBean walletBean) {
                curAddress = walletBean.getAddress();
                curAccount = accountDao.getAccount(curAddress);

                tvWallet.setText(walletBean.getAccountName());
                tvPay.setText(walletBean.getAddress());
                if (ipaChainId == IPAssetsConstant.CHAIN_ID_BTC) {
                    UTXOTransactionManager.getBalance( TAG, curAccount);
                }
                if (ipaChainId == EosNetParamUtil.getEosChainId()) {
                    tvAccount.setText(walletBean.getAddress());
                }
                setPayData();
                requestAccountBalance();
            }
        });
    }

    /**
     * 选择账户
     */
    private String[] items;

    private void changeAccountAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        int checkedItem = 0;
        if (curAccount.getEosAccountNames() == null || curAccount.getEosAccountNames().equals("")) {
            items = new String[]{curAccount.getAddress()};
        } else {
            items = curAccount.getEosAccountNames().split("_");

            for (int i = 0; i < items.length; i++) {
                if (curAccount.getAddress().equals(items[i])) {
                    checkedItem = i;
                }
            }
        }
        builder.setTitle(ResStringUtil.getString(R.string.open_planet_choose_account))
                .setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        curAddress = items[i];
                        tvAccount.setText(curAddress);
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //显示转账确认界面
    private void showTransferConfirm() {
        if (curAccount == null) {
            ToastUtils.showShort(R.string.open_planet_account_exception);
            return;
        }
        if (curAccount.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
            ToastUtils.showShort(R.string.open_planet_observe_account_not_allowed);
            return;
        }

        try {
            double money = Double.parseDouble(etMoney.getText().toString());
            double balance = Double.parseDouble(tvBalance.getText().toString().replaceAll("[, ]",""));
            if (money > balance) {
                ToastUtils.showShort(R.string.open_planet_amount_should_not_big_than_balance);
                return;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            ToastUtils.showShort(R.string.open_planet_amount_exchange_error);
            return;
        }

        AssetListBean assetListBean = null;
        if (assetsBean.getCoinAddress() != null && !"".equals(assetsBean.getCoinAddress())) {
            assetListBean = new AssetListBean();
            assetListBean.setAddress(assetsBean.getCoinAddress());
            assetListBean.setBalance("");
            assetListBean.setBlockChainID(ipaChainId + "");
            assetListBean.setName(assetsBean.getCoinName());
            assetListBean.setSecondName(assetsBean.getCoinFullName());
            assetListBean.setId(assetsBean.getTrusteeshipId() + "");
        }

        String gas = blockFeeSekbar.getProgressGas();
        String convertGas = blockFeeSekbar.getGasConversion();
        RechargeDialogFragment rechargeDialogFragment = new
                RechargeDialogFragment();
        rechargeDialogFragment.setTrusteeshipId(assetsBean.getTrusteeshipId() + "");
        rechargeDialogFragment.setData(this, ipaChainId,
                etMoney.getText().toString(), "",
                assetsBean.getSysAddress(), curAddress, curAccount.getAcccountName(),
                gas,convertGas, assetListBean);
        rechargeDialogFragment.setStyle(DialogFragment.STYLE_NO_FRAME, 0);
        rechargeDialogFragment.show(getSupportFragmentManager(), "TransferConfirm");
    }
}
